#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
    int cutOffTree(vector<vector<int>>& forest) {
        if (forest.empty() || forest[0].empty()) return 0;
        int m = forest.size(), n = forest[0].size();
        vector<vector<int>> trees;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (forest[i][j] > 1) {
                    trees.push_back({ forest[i][j], i, j });
                }
            }
        }
        sort(trees.begin(), trees.end());
        int totalSteps = 0;
        int startX = 0, startY = 0;
        for (auto& tree : trees) {
            int height = tree[0], targetX = tree[1], targetY = tree[2];
            int steps = bfs(forest, startX, startY, targetX, targetY, m, n);
            if (steps == -1) return -1;
            totalSteps += steps;
            startX = targetX;
            startY = targetY;
            forest[targetX][targetY] = 1;
        }

        return totalSteps;
    }

private:
    int bfs(vector<vector<int>>& forest, int sx, int sy, int tx, int ty, int m, int n) {
        if (sx == tx && sy == ty) return 0;

        vector<pair<int, int>> dirs = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        queue<pair<int, int>> q;

        q.push({ sx, sy });
        visited[sx][sy] = true;
        int steps = 0;

        while (!q.empty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                auto [x, y] = q.front();
                q.pop();

                for (auto [dx, dy] : dirs) {
                    int nx = x + dx, ny = y + dy;
                    if (nx >= 0 && nx < m && ny >= 0 && ny < n &&
                        !visited[nx][ny] && forest[nx][ny] != 0) {
                        if (nx == tx && ny == ty) return steps + 1;
                        visited[nx][ny] = true;
                        q.push({ nx, ny });
                    }
                }
            }
            steps++;
        }

        return -1;
    }
};